from flask import flash, redirect, url_for, render_template, request
from . import web
from flask_login import login_required, current_user
from app.models.gift import Gift
from app.forms.book import DriftFrom
from app.models.base import db
from app.models.drift import Drift
from app.models.user import User
from app.models.wish import Wish
from app.view_models.book import BookViewModel
from app.libs.email import send_mail
from sqlalchemy import desc, or_
from app.view_models.drift import DriftCollection
from app.libs.enums import PendingStatus


@web.route('/drift/<int:gid>', methods=['GET', 'POST'])
@login_required
def send_drift(gid):
    current_gift = Gift.query.get_or_404(gid)
    if current_gift.is_yourself_gift(current_user.id):
        flash('这本书是你自己的^_^, 不能向自己索要书籍噢')
        return redirect(url_for('web.book_detail', isbn=current_gift.isbn))
    if not current_user.can_send_drift():
        return render_template('not_enough_beans.html', beans=current_user.beans)
    # 赠送者信息
    gifter = current_gift.user.summary
    # 索要者信息
    user_beans = current_user.beans

    form = DriftFrom(request.form)
    if request.method == 'POST' and form.validate():
        save_drift(form, current_gift)
        # 邮件通知赠送者
        send_mail(current_gift.user.email, '有人想要一本书', 'email/get_gift.html', wisher=current_user, gift=current_gift)
        return redirect(url_for('web.pending'))
    return render_template('drift.html', gifter=gifter, user_beans=user_beans, form=form)


@web.route('/pending')
@login_required
def pending():
    """
    鱼漂
    :return:
    """
    drifts = Drift.query.filter(
        or_(Drift.requester_id == current_user.id, Drift.gifter_id == current_user.id)
    ).order_by(desc(Drift.create_time)).all()

    drifts_view = DriftCollection(drifts, current_user.id)

    return render_template('pending.html', drifts=drifts_view.data)


@web.route('/drift/<int:did>/reject')
def reject_drift(did):
    """
    拒绝用户索要
    :param did:
    :return:
    """
    with db.auto_commit():
        drift = Drift.query.filter(
            Drift.id == did, Gift.uid == current_user.id
        ).first_or_404()
        drift.pending = PendingStatus.Reject
        requester = User.query.get_or_404(drift.requester_id)
        requester.beans += 1
    return redirect(url_for('web.pending'))


@web.route('/drift/<int:did>/redraw')
def redraw_drift(did):
    """
    撤销索要
    :param did:
    :return:
    """
    with db.auto_commit():
        # 交易状态更新为撤销
        drift = Drift.query.filter_by(id=did, requester_id=current_user.id).first_or_404()
        drift.pending = PendingStatus.Redraw
        # 返还索要者鱼豆
        current_user.beans += 1
    return redirect(url_for('web.pending'))


@web.route('/drift/<int:did>/mailed')
def mailed_drift(did):
    """
    邮寄书籍
    :param did:
    :return:
    """
    with db.auto_commit():
        # 交易状态更新为成功
        drift = drift = Drift.query.filter_by(id=did, gifter_id=current_user.id).first_or_404()
        drift.pending = PendingStatus.Success
        # 赠送用户获取鱼豆奖励
        current_user.beans += 1
        # 更新赠送状态
        gift = Gift.query.filter_by(id=drift.gift_id).first_or_404()
        gift.launched = True
        # 更新心愿状态
        wish = Wish.query.filter_by(isbn=drift.isbn, uid=drift.requester_id, launched=False).first_or_404()
        wish.launched = True
    return redirect(url_for('web.pending'))


def save_drift(drift_form, current_gift):
    """
    保存用户索取书籍信息
    :param drift_form:
    :param current_gift:
    :return:
    """
    with db.auto_commit():
        drift = Drift()
        # 将表彰数据赋值到对象
        drift_form.populate_obj(drift)
        # 礼物信息
        drift.gift_id = current_gift.id
        # 索要者信息
        drift.requester_id = current_user.id
        drift.requester_nickname = current_user.nickname
        # 赠送者信息
        drift.gifter_id = current_gift.user.id
        drift.gifter_nickname = current_gift.user.nickname
        # 书籍信息
        book = BookViewModel(current_gift.book)
        drift.isbn = book.isbn
        drift.book_title = book.title
        drift.book_author = book.author
        drift.book_img = book.image
        # 扣除索要者鱼豆
        current_user.beans -= 1

        db.session.add(drift)
